// pages/Goods/Commit/index.js
var common = require("../../../../public.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: [],
    itemId: 0, // 商品id
    storeId: 0, // 店铺id
    goodsInfo: '', //商品信息
    storeInfo: '', //店铺信息
    totalPostType: [], //根据店铺返回的共有多少个配送方式
    active: 0, //默认选中配送方式  开始根据下标0开始
    postage: 0, //邮费默认值
    postType: '', //默认配送方式
    postTypeName: '', // 默认配送方式名称
    price: 0, //单价
    num: 1, //数量
    pickUpName: '', // 自提人
    pickUpPhone: '', // 自提手机号
    receiverName: '', // 收货人
    receiverMobile: '', // 收货人手机
    receiverAddress: '',
    receiverId: '',
    currentPost: {}, // 当前选中配送方式
    selectedAddr: false
  },
  onLoad: function (options) {
    const that = this
    if (options.selectedAddr) {
      that.setData({
        selectedAddr: options.selectedAddr,
        receiverName: options.receiverName,
        receiverMobile: options.receiverMobile,
        receiverAddress: options.receiverAddress,
        receiverId: options.id,
      })
    } else {
      common.getLocalUserInfo(function (success, userInfo) {
        if (success) {
          getApp().getLocation(function (data) {
            that.setData({
              xpoint: data.longitude,
              ypoint: data.latitude
            }, _ => {
              that.getPostType() //根据位置查询店铺配送方式
            })
          })
          that.setData({
            userInfo: userInfo.user,
            token: userInfo.token,
            openid: userInfo.openid,
            itemId: options.itemId,
            storeId: options.storeId,
            pickUpName: userInfo.user.realName,
            pickUpPhone: userInfo.user.phone,
            active: 0,
          }, () => {
            that.getGoodsDes() //查询商品详情信息
            that.getShopDes()
          })
        }
      }, true)
    }

  },
  //查询商品详情信息
  getGoodsDes: function () {
    var that = this
    let tempJson = {
      zerobuyId: that.data.itemId
    }
    common.wxRequest("/selectZerobuyById", "post", tempJson, 'application/x-www-form-urlencoded', function (res) {
      console.log('商品详情', res)
      that.setData({
        goodsInfo: res.data
        // totalMoney:
      })
    })
  },

  //查询店铺信息
  getShopDes() {
    var that = this
    let tempJson = {
      storeId: that.data.storeId
    }
    common.wxRequest("/store/info", "post", tempJson, 'application/x-www-form-urlencoded', function (res) {
      console.log('店铺详情,', res)
      that.setData({
        storeInfo: res.data,
      })
    })
  },
  //查询店铺配送方式
  getPostType() {
    var that = this
    var tempJson = {
      storeId: that.data.storeId,
      userId: that.data.userInfo.id,
      xpoint: that.data.xpoint,
      ypoint: that.data.ypoint
    };
    common.post("/store/getPostTypeNew", tempJson, function (res) {
      if (res.status === 200) {
        that.setData({
          totalPostType: res.data,
          // postType: res.data[0].feeType,
          // postage: res.data[0].price,
          // postTypeName: res.data[0].dname,
          currentPost: res.data[that.data.active],
          active: 0
        }, function () {
          // Tabs 组件在挂载时，会获取自身的宽度，并计算出底部条的位置。
          // 如果组件一开始处于隐藏状态，则获取到的宽度永远为 0，因此无法展示底部条位置。
          that.selectComponent('#tabs').resize()
        })
      } else {
        common.showRequestErrMsg(res)
      }
    })
  },
  //点击选中的配送方式
  onChange(event) {
    var that = this;
    that.setData({
      receiverName: '',
      receiverMobile: '',
      receiverId: '',
      selectedAddr: false
    })
    // let feeType = event.detail.feeType
    console.log('event', event.detail.index)
    let index = event.detail.index

    this.setData({
      currentPost: this.data.totalPostType[index]
    })
  },
  commit() {
    if (this.data.currentPost.feeType == 2 && common.isEmptyString(this.data.pickUpName)) {
      common.showToast('请输入提货人')
      return
    }
    if (this.data.currentPost.feeType == 2 && common.isEmptyString(this.data.pickUpPhone)) {
      common.showToast('请输入提货人手机号')
      return
    }
    if (this.data.currentPost.feeType != 2 && !this.data.selectedAddr) {
      common.showToast('请选择地址')
      return
    }
    const that = this
    const tempJson = {
      token: that.data.token,
      zerobuyId: that.data.itemId,
      userId: that.data.userInfo.id,
      buyNum: that.data.num,
      receiverName: that.data.receiverName || that.data.pickUpName,
      receiverMobile: that.data.receiverMobile || that.data.pickUpPhone,
      expressPrice: that.data.currentPost.price,
      postType: that.data.currentPost.feeType,
      os: 'android',
      shippingId: that.data.receiverId
    }
    common.post('/createZeroBuyOrder', tempJson, function (res) {
      if (res.status == 200) {
        let payParam = {
          userId: that.data.userInfo.id,
          token: that.data.token,
          orderId: res.data.id,
          openid: that.data.openid,
        }

        common.wxPayRequest('/wxxcxPayForZeroGoods', payParam, function (payRes) {
          wx.requestPayment({
            'timeStamp': payRes.data.timeStamp,
            'nonceStr': payRes.data.nonceStr,
            'package': payRes.data.package,
            'signType': payRes.data.signType,
            'paySign': payRes.data.paySign,
            'success': function (res) {
              common.showToast('支付成功', 'success')
              wx.redirectTo({
                url: '/packageC/pages/Order/zeroOrder/index',
            })
            },
            'fail': function (res) {
              wx.redirectTo({
                url: '/packageC/pages/Order/zeroOrder/index',
              })
              if (res.errMsg === 'requestPayment:fail cancel') {
              } else {
                common.showToast(res.errMsg)
              }
            }
          })
        })
      } else {
        common.showRequestErrMsg(res)
      }
    })
  },
  onChangeText(event) { },
})